package cn.dvptech.remotecontrol.screenmirror.virtualDisplay;

import android.graphics.SurfaceTexture;
import android.opengl.GLES20;
import android.opengl.GLES30;

import java.nio.FloatBuffer;

/**
 * Date: 2023/4/23
 * Author: ulongx
 * Project Name: DrivingMate
 * desc:
 */
public class GLXSurfaceRenderer implements ITextureRenderer{
    private static final String fragment_shader = "#extension GL_OES_EGL_image_external : require\nprecision mediump float;\nvarying vec4 vTextureCoord;\nuniform samplerExternalOES sTexture;\nvoid main() {\n    gl_FragColor = texture2D(sTexture, vTextureCoord.xy);}\n";
    private static final String vertex_shader = "attribute vec4 aPosition;\nattribute vec4 aTextureCoord;\nvarying vec4 vTextureCoord;\nvoid main() {\n    gl_Position = aPosition;\n    vTextureCoord = aTextureCoord;\n}\n";
    private int mProgram;
    private int mTextureID;
    private int aPositionLocation;
    private int aTextureCoordLocation;
    private FloatBuffer vertexBuffer;
    private FloatBuffer fragmentBuffer;

    // 构造函数用于初始化顶点和片段缓冲区
    public GLXSurfaceRenderer() {
        this.vertexBuffer = AllocateUtis.createFloatBuffer(new float[]{-1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f});
        this.fragmentBuffer = AllocateUtis.createFloatBuffer(new float[]{0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f});
    }

    // 当表面创建时调用
    @Override
    public void onSurfaceCreated() {
        this.mProgram = ShaderUtils.linkProgram30(ShaderUtils.compileVertexShader30(vertex_shader), ShaderUtils.compileFragmentShader30(fragment_shader));
        this.aPositionLocation = GLES20.glGetAttribLocation(this.mProgram, "aPosition");
        this.aTextureCoordLocation = GLES20.glGetAttribLocation(this.mProgram, "aTextureCoord");
        this.mTextureID = TextureUtils.loadTexture30();
    }

    // 获取纹理ID
    public int getmTextureID() {
        return this.mTextureID;
    }

    // 当需要绘制帧时调用
    @Override
    public void onDrawFrame(SurfaceTexture surfaceTexture) {
        GLES30.glUseProgram(this.mProgram);
        GLES30.glEnableVertexAttribArray(this.aPositionLocation);
        GLES30.glVertexAttribPointer(this.aPositionLocation, 2, GLES30.GL_FLOAT, false, 8, this.vertexBuffer);
        GLES30.glEnableVertexAttribArray(this.aTextureCoordLocation);
        GLES30.glVertexAttribPointer(this.aTextureCoordLocation, 2, GLES30.GL_FLOAT, false, 8, this.fragmentBuffer);
        GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
        GLES30.glDisableVertexAttribArray(this.aPositionLocation);
        GLES30.glDisableVertexAttribArray(this.aTextureCoordLocation);
        GLES30.glUseProgram(0);
    }

}
